package com.ddd.utils;


import com.ddd.utils.redis.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by zhouxj6112 on 2019/12/15.
 */
@Component
public class UserTokenUtil {
    @Autowired
    private RedisUtil redisUtil;


    @Value("${token_secret_key}")
    private static  String token_secret_key;

    private static long delay_time = 7*24*3600;

    public static String generateUserToken(Long userId) {
        long currentTime = System.currentTimeMillis()/1000;
        long expireTime = 30*24*3600;
        String content = userId + "&" + currentTime + "&" + expireTime;
        String userToken = AESUtil.encrypt(content, token_secret_key);
        return userToken;
    }

    public Long fetchUserId(String userToken, Map<String, List<String>> paras) {
        String[] data = parseToken(userToken);
        if (data == null) {
            return null;
        }
        if (!data[0].equals("new")) {
            Long currentTime = Long.valueOf(data[1]);
            Long expireTime = Long.valueOf(data[2]) + currentTime;
            if (System.currentTimeMillis() / 1000 > expireTime) {
                // 当前userToken已经过期了
                return null;
            }
            // 验证token版本
            if (data.length < 4 ) {
                return null;
            }
            return Long.valueOf(data[0]);
        }else {
            Object o = redisUtil.get(userToken);
            if (o == null || data.length != 4) {
                return null;
            } else {
                try {
                    Map<String, Object> session = (Map<String, Object>) o;
                    session.forEach((k, v) -> {
                        if(!Objects.isNull(v)) {
                            List<String> list = new ArrayList<>();
                            list.add(v.toString());
                            paras.put(k, list);
                        }
                    });
                } catch (Exception e) {
                }
                long expire = redisUtil.getExpire(userToken);
                if (expire < delay_time){
                    redisUtil.set(userToken, o, expire + delay_time);
                    redisUtil.set(data[2]+userToken, 1, expire + delay_time);
                }
            }
            return Long.valueOf(data[2]);
        }
    }

    public static String[] parseToken(String userToken) {
        String content = AESUtil.decrpyt(userToken, token_secret_key).trim();
        if (content == null) {
            return null;
        }
        String[] data = content.split("&");
        return data;
    }

}
